package cn.itlaobing.eshopmanagement.service.impl;

import java.util.Date;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.itlaobing.eshopmanagement.entity.SystemAccount;
import cn.itlaobing.eshopmanagement.mapper.SystemAccountMapper;
import cn.itlaobing.eshopmanagement.service.SessionService;

@Service
public class SessionServiceImpl implements SessionService {
	@Autowired
	private SystemAccountMapper systemAccountMapper;

	private String defaultPassword = "123456";

	@Override
	public SystemAccount create(String account,String realName) {
		// 产生随机的盐值 16个字符的随机数 字母与数字混合
		String salt = RandomStringUtils.random(16, true, true);
		// 密文
		String passwordDigest = crypt(defaultPassword, salt);
		SystemAccount acc = new SystemAccount();
		acc.setAccount(account);//登录名
		acc.setRealName(realName);
		acc.setPasswordDigist(passwordDigest);//密文密码
		acc.setSalt(salt);//盐值
		acc.setCreateAt(new Date());//创建时间
		acc.setLocked(false);//未锁定
		acc.setStatus(1);//普通管理员
		acc.setIsDeleted(false);
		systemAccountMapper.insertSelective(acc);
		return acc;
	}

	/**
	 * 加密
	 * 
	 * @return
	 */
	private String crypt(String password, String salt) {
		// 先对原始密码加密
		String passwordCrypt = DigestUtils.md5Hex(password + salt);
		StringBuffer sb=new StringBuffer();
		for (int i = 0; i < passwordCrypt.length(); i++) {
			//如果是字母就跳过
			if(Character.isLetter(passwordCrypt.charAt(i))){
				continue;
			}
			sb.append(passwordCrypt.charAt(i));
		}
		//返回倒序结果
		return StringUtils.reverse(sb.toString());
	}

	@Override
	public SystemAccount validate(String account, String password) {
		SystemAccount acc = systemAccountMapper.selectByPrimaryAccount(account);
		if (acc == null) { // 找不到账号，返回null
			return null;
		}
		
		// 验证密码
		String passwordDigest = crypt(password, acc.getSalt());

		// 正确的密码
		String realPasswordDigest = acc.getPasswordDigist();

		// 正确
		if (passwordDigest.equals(realPasswordDigest)) {
			return acc;
		}

		return null;
	}

	@Override
	public void updateLastSignInDateTime(String account) {
		SystemAccount acc=systemAccountMapper.selectByPrimaryAccount(account);
		if(acc!=null){
			acc.setLastLoginAt(new Date());
			systemAccountMapper.updateByPrimaryKeySelective(acc);
		}
	}

	@Override
	public void update(SystemAccount account) {
		// 产生随机的盐值 16个字符的随机数 字母与数字混合
		String salt = RandomStringUtils.random(16, true, true);
		String passwordDigest = crypt(account.getPasswordDigist(), salt);
		account.setPasswordDigist(passwordDigest);
		account.setSalt(salt);
		account.setUpdateAt(new Date());
		systemAccountMapper.updateByPrimaryKeySelective(account);
	}
	
}
